package com.carboy.launch.activity.setting;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Spinner;
import android.widget.TextView;

import com.carboy.launch.BaseApplication;
import com.carboy.launch.R;
import com.carboy.launch.activity.column.BaseActivity;
import com.carboy.launch.widgets.CustomToast;
import com.carboy.launch.widgets.LightenessOperateDialog;

/**
 * 显示设置Activity
 */
public class SDisplaySettingActivity extends BaseActivity implements
		OnClickListener {

	// 当前上下文
	private Context mContext;

	// ================== 控件View =================
	private ImageView asds_break_igview; // 返回键
	private CheckBox asds_lockscreen_checkBox; // 锁定屏幕通知
	private CheckBox asds_rotationscreen_checkBox; // 自动旋转屏幕
	private LinearLayout asds_lighteness_linear; // 亮度
	private LinearLayout asds_dormancy_linear; // 休眠时间
	private LinearLayout asds_fontsize_linear; // 字体大小
	private TextView asds_dormancy_tv; // 休眠时间
	private TextView asds_fontsize_tv; // 字体大小
	private Spinner asds_spinner; // 下拉选择
	// ================== 其他对象 =================
	private boolean isType = true; // 判断类型 true = 休眠时间，false = 字体大小
	private int[] typeSelect = new int[] { 0, 0 }; // 对应类型选中的索引
	private String[] dormancyTimes ;
	private String[] fontSizes;
	boolean isOperate = false; // 判断是否开始操作
	private LightenessOperateDialog lODialog; // 亮度操作Dialog
	private Dialog lDialog; // 亮度操作Dialog

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setting_display_setting);
		mContext = SDisplaySettingActivity.this;

		initViews();
		initStatusBar();
		initValues();
		initListeners();
	}

	/**
	 * 初始化控件
	 */
	private void initViews() {
		asds_break_igview = (ImageView) this
				.findViewById(R.id.asds_break_igview); // 返回键
		asds_lockscreen_checkBox = (CheckBox) this
				.findViewById(R.id.asds_lockscreen_checkBox); // 锁定屏幕通知
		asds_rotationscreen_checkBox = (CheckBox) this
				.findViewById(R.id.asds_rotationscreen_checkBox); // 自动旋转屏幕
		asds_lighteness_linear = (LinearLayout) this
				.findViewById(R.id.asds_lighteness_linear); // 亮度
		asds_dormancy_linear = (LinearLayout) this
				.findViewById(R.id.asds_dormancy_linear); // 休眠时间
		asds_fontsize_linear = (LinearLayout) this
				.findViewById(R.id.asds_fontsize_linear); // 字体大小
		asds_dormancy_tv = (TextView) this.findViewById(R.id.asds_dormancy_tv); // 休眠时间
		asds_fontsize_tv = (TextView) this.findViewById(R.id.asds_fontsize_tv); // 字体大小
		asds_spinner = (Spinner) this.findViewById(R.id.asds_spinner); // 下拉选择
	}

	/**
	 * 初始化参数
	 */
	private void initValues() {
		lODialog = new LightenessOperateDialog(mContext);
		dormancyTimes = getResources().getStringArray(R.array.dormancy_times);
		fontSizes = getResources().getStringArray(R.array.font_sizes);
	}

	/**
	 * 初始化事件
	 */
	private void initListeners() {
		asds_break_igview.setOnClickListener(this);
		asds_lighteness_linear.setOnClickListener(this);
		asds_dormancy_linear.setOnClickListener(this);
		asds_fontsize_linear.setOnClickListener(this);
		asds_lockscreen_checkBox.setOnClickListener(this);
		asds_rotationscreen_checkBox.setOnClickListener(this);
		asds_spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> aView, View view,
					int pos, long id) {
				// BaseApplication.playClickVoice(mContext);
				if (!isOperate) {
					isOperate = true;
					return;
				}
				typeSelect[isType ? 0 : 1] = pos; // 设置索引
				try {
					if (isType) { // 设置休眠时间
						int time = 2147483647;
						switch (pos) {
						case 0:
							time = 30000;
							break;
						case 1:
							time = 60000;
							break;
						case 2:
							time = 120000;
							break;
						case 3:
							time = 300000;
							break;
						case 4:
							time = 600000;
							break;
						case 5:
							time = 1800000;
							break;
						default:
							time = 2147483647;
							break;
						}
						asds_dormancy_tv.setText(dormancyTimes[pos]);
						Settings.System
								.putInt(getContentResolver(),
										android.provider.Settings.System.SCREEN_OFF_TIMEOUT,
										time);
					} else { // 设置字体大小
						float fontSize = 0.85f;
						switch (pos) {
						case 0:
							fontSize = 1.0f;
							break;
						case 1:
							fontSize = 1.1f;
							break;
						case 2:
							fontSize = 1.2f;
							break;
						case 3:
							fontSize = 1.30f;
							break;
						}
						asds_fontsize_tv.setText(fontSizes[pos]);

						setFontScale(fontSize);

					}
				} catch (Exception e) {
					CustomToast.showToast(mContext, R.string.operate_failure);
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
	}

	/**
	 * 点击事件
	 */
	@Override
	public void onClick(View v) {
		BaseApplication.playClickVoice(mContext);
		switch (v.getId()) {
		case R.id.asds_break_igview: // 返回键
			SDisplaySettingActivity.this.finish();
			break;
		case R.id.asds_lockscreen_checkBox: // 锁定屏幕通知
			if (asds_lockscreen_checkBox.isChecked()) {
				Settings.System.getInt(mContext.getContentResolver(),
						INCOMING_INDICATOR_ON_LOCKSCREEN,
						DEFAULT_LOCK_SCREEN_NOTIFICATIONS);
			} else {
				Settings.System.getInt(mContext.getContentResolver(),
						INCOMING_INDICATOR_ON_LOCKSCREEN, 0);
			}
			break;
		case R.id.asds_rotationscreen_checkBox: // 自动旋转屏幕
			if (asds_rotationscreen_checkBox.isChecked()) {
				Settings.System.putInt(getContentResolver(),
						Settings.System.ACCELEROMETER_ROTATION, 1);
			} else {
				Settings.System.putInt(getContentResolver(),
						Settings.System.ACCELEROMETER_ROTATION, 0);
			}
			break;
		case R.id.asds_lighteness_linear: // 亮度
			showLightDialog();
			break;
		case R.id.asds_dormancy_linear: // 休眠时间
			setSpinner(true, dormancyTimes, getResources().getString(R.string.dormancy_hint));
			break;
		case R.id.asds_fontsize_linear: // 字体大小
			setSpinner(false, fontSizes, getResources().getString(R.string.fontsize_hint));
			break;
		}
	}

	/**
	 * 重写返回键
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			SDisplaySettingActivity.this.finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onPause() {
		super.onPause();

	}

	@Override
	protected void onResume() {
		super.onResume();

		displayMsg();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		// Activity被回收,则保存数据
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// 切屏触发
	}

	// ======================= 选项操作 ========================
	private void setSpinner(boolean isType, String[] sData, String title) {
		this.isType = isType;
		asds_spinner.setPrompt(title);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, sData);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		asds_spinner.setAdapter(adapter);
		asds_spinner.setSelection(typeSelect[isType ? 0 : 1], true);
		asds_spinner.performClick();

		isOperate = false;
	}

	private void showLightDialog() {
		if (lDialog == null) {
			// 得到屏幕宽、高度
			Display display = this.getWindowManager().getDefaultDisplay();
			int width = display.getWidth();
			int height = display.getHeight();

			AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
			builder.setTitle("亮度");
			// 使用外部自定义布局时，加载外部xml
			LayoutInflater inflater = LayoutInflater.from(mContext);
			View view = inflater.inflate(R.layout.dialog_lighteness, null);
			// 直接调用 builder.setView(view);则绑定成功
			SeekBar seekBar = (SeekBar) view
					.findViewById(R.id.dl_lightnumber_seekbar);
			seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
				@Override
				public void onStopTrackingTouch(SeekBar seekBar) {
					// 该方法拖动进度条开始拖动的时候调用。

				}

				@Override
				public void onStartTrackingTouch(SeekBar seekBar) {
					// 该方法拖动进度条停止拖动的时候调用

				}

				@Override
				public void onProgressChanged(SeekBar seekBar, int progress,
						boolean fromUser) {
					// 该方法拖动进度条进度改变的时候调用
					Settings.System.putInt(getContentResolver(),
							Settings.System.SCREEN_BRIGHTNESS, progress + 30);
				}
			});
			seekBar.setLayoutParams(new LayoutParams(width / 3,
					LayoutParams.WRAP_CONTENT));

			// 获取系统亮度
			try {
				int progress = Settings.System.getInt(getContentResolver(),
						Settings.System.SCREEN_BRIGHTNESS);
				seekBar.setProgress(progress - 30);
			} catch (SettingNotFoundException e) {
				e.printStackTrace();
			}

			builder.setView(view);
			lDialog = builder.create();
		}
		lDialog.show();
	}

	private static final String INCOMING_INDICATOR_ON_LOCKSCREEN = "incoming_indicator_on_lockscreen";
	private static final int DEFAULT_LOCK_SCREEN_NOTIFICATIONS = 1;

	// ======================= 系统显示数据操作 ===========================
	private void displayMsg() {
		try {
			// 获得锁定屏幕通知状态
			asds_lockscreen_checkBox.setChecked(Settings.System.getInt(
					mContext.getContentResolver(),
					INCOMING_INDICATOR_ON_LOCKSCREEN,
					DEFAULT_LOCK_SCREEN_NOTIFICATIONS) == 1);
		} catch (Exception e) {
			// TODO: handle exception
		}
		try {
			// 获取屏幕是否自动旋转
			asds_rotationscreen_checkBox.setChecked(isRotationLocked(mContext));
		} catch (Exception e) {
		}
		try {
			// 获得休眠时间
			int offTimeOut = Settings.System.getInt(getContentResolver(),
					android.provider.Settings.System.SCREEN_OFF_TIMEOUT);
			//Toast.makeText(getApplicationContext(), offTimeOut+"", 3000).show();
			int offPos = 0;
			if (0 < offTimeOut &&  offTimeOut <= 30000) {
				offPos = 0;
			} else if (30000 < offTimeOut && offTimeOut <= 60000) {
				offPos = 1;
			} else if (60000 < offTimeOut && offTimeOut <= 120000) {
				offPos = 2;
			} else if (120000 < offTimeOut && offTimeOut <= 300000) {
				offPos = 3;
			} else if (300000 < offTimeOut && offTimeOut <= 600000) {
				offPos = 4;
			} else if (600000 < offTimeOut && offTimeOut <= 1800000) {
				offPos = 5;
			} else {
				offPos = 6;
			}
			asds_dormancy_tv.setText(dormancyTimes[offPos]);
			typeSelect[0] = offPos; // 设置索引
		} catch (SettingNotFoundException e) {
			e.printStackTrace();
		}
		try {
			float fontScale = Settings.System.getFloat(getContentResolver(),
					android.provider.Settings.System.FONT_SCALE);
			int fontPos = 0;
			if (fontScale <= 1.0f) {
				fontPos = 0;
			} else if (fontScale <= 1.10f) {
				fontPos = 1;
			} else if (fontScale <= 1.20f) {
				fontPos = 2;
			} else if (fontScale <= 1.30f) {
				fontPos = 3;
			}
			asds_fontsize_tv.setText(fontSizes[fontPos]);
			typeSelect[1] = fontPos; // 设置索引
		} catch (SettingNotFoundException e) {
			e.printStackTrace();
		}
	}

	private void setFontScale(float fontScale) {
		final Configuration mCurConfig = new Configuration();

		try {
			// mCurConfig.updateFrom(ActivityManagerNative.getDefault()
			// .getConfiguration());
			// ActivityManagerNative.getDefault().updatePersistentConfiguration(
			// mCurConfig);
			// mCurConfig.fontScale = fontScale;
			// ActivityManagerNative.getDefault().updatePersistentConfiguration(
			// mCurConfig);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void setFontSize(Configuration config) {
		Method method;
		try {
			Class<?> activityManagerNative = Class
					.forName("android.app.ActivityManagerNative");
			try {
				Object am = activityManagerNative.getMethod("getDefault")
						.invoke(activityManagerNative);
				method = am.getClass().getMethod("updateConfiguration",
						android.content.res.Configuration.class);
				method.invoke(am, config);// 设置字体大小的方法就是
				try {
					// ActivityManagerNative.getDefault().updateConfiguration(
					// config);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public static boolean isRotationLocked(Context context) {
		// return
		// Settings.System.getIntForUser(context.getContentResolver(),Settings.System.ACCELEROMETER_ROTATION,
		// 0, UserHandle.USER_CURRENT) == 0;
		return Settings.System.getInt(context.getContentResolver(),
				Settings.System.ACCELEROMETER_ROTATION, 0) == 1;
	}

}
